package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdminLoginService;
import com.heima.model.admin.dto.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.sql.Wrapper;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class AdminLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdminLoginService {

    @Resource
    private AdUserMapper adUserMapper;

    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        if (StringUtils.isNotBlank(adUserDto.getName())&&StringUtils.isNotBlank(adUserDto.getPassword())) {
//            查询账号是否存在
            LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AdUser::getName,adUserDto.getName());
            AdUser adUser = adUserMapper.selectOne(queryWrapper);
            if (adUser==null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"数据不存在");
            }
            //比对密码
            String salt = adUser.getSalt();
            String password = adUserDto.getPassword();
            String pswd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if(!pswd.equals(adUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

//            返回数据
            String token = AppJwtUtil.getToken(adUser.getId().longValue());
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            adUser.setSalt("");
            adUser.setPassword("");
            map.put("user",adUser);

            return ResponseResult.okResult(map);
        } else {
            log.error("用户账号和密码必须填写！");
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"数据不存在");
        }
    }
}
